//
//  StatisticsViewController.m
//  CheckersGame
//
//  Created by Guest User on 11-12-02.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "StatisticsViewController.h"
#import "GameManagedObject.h"
#import "AppDelegate.h"//fix this

@interface StatisticsViewController ()
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;
@end

@implementation StatisticsViewController
@synthesize table;
@synthesize statArray;
@synthesize segcomp;
@synthesize fetchedResultsController = __fetchedResultsController;
@synthesize managedObjectContext = __managedObjectContext;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    statArray = [[NSMutableArray alloc] init];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"Statistics";
    //self.tableController.delegate = self.tableController;
    //[self fetchRecords:NO]; //hardcode start segment selected
    table.delegate = self;
    
    self.managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
    
    NSDictionary *testgame1 = [NSDictionary dictionaryWithObjectsAndKeys:
                               [NSDate date], @"date",
                               @"1", @"draw",
                               @"1", @"pvp",
                               @"bob", @"player1",
                               @"ted", @"player2", nil];
    
    NSDictionary *testgame2 = [NSDictionary dictionaryWithObjectsAndKeys:
                               [NSDate date], @"date",
                               @"0", @"draw",
                               @"1", @"pvp",
                               @"lucy", @"player1",
                               @"sasha", @"player2", nil];
    
    NSDictionary *testgame3 = [NSDictionary dictionaryWithObjectsAndKeys:
                               [NSDate date], @"date",
                               @"1", @"draw",
                               @"0", @"pvp",
                               @"bob", @"player1",
                               @"cpu", @"player2", nil];
    
    NSDictionary *testgame4 = [NSDictionary dictionaryWithObjectsAndKeys:
                               [NSDate date], @"date",
                               @"0", @"draw",
                               @"0", @"pvp",
                               @"cpu", @"player1",
                               @"ted", @"player2", nil];
    
    
    NSDictionary *testplayer1 = [NSDictionary dictionaryWithObjectsAndKeys:
                                 @"Sarah", @"name",
                                 @"0", @"ai",
                                 @"5", @"wins",
                                 @"1", @"draws",
                                 @"0", @"loses", nil];
    /*    
     NSDictionary *testplayer2 = [NSDictionary dictionaryWithObjectsAndKeys:
     @"Becky", @"name",
     @"0", @"ai",
     @"7", @"wins",
     @"2", @"draws",
     @"1", @"loses", nil];
     */
    NSDictionary *testplayer3 = [NSDictionary dictionaryWithObjectsAndKeys:
                                 @"CPU1", @"name",
                                 @"1", @"ai",
                                 @"9", @"wins",
                                 @"5", @"draws",
                                 @"3", @"loses", nil];
    /*
     NSDictionary *testplayer4 = [NSDictionary dictionaryWithObjectsAndKeys:
     @"CPU2", @"name",
     @"2", @"ai",
     @"12", @"wins",
     @"1", @"draws",
     @"1", @"loses", nil];
     */
    //[GameManagedObject gameWithResult:testgame1 inManagedContext:self.managedObjectContext];
    //[GameManagedObject gameWithResult:testgame2 inManagedContext:self.managedObjectContext];
    //[GameManagedObject gameWithResult:testgame3 inManagedContext:self.managedObjectContext];
    //[GameManagedObject gameWithResult:testgame4 inManagedContext:self.managedObjectContext];
    //[PlayerManagedObject playerWithResult:testplayer1 inManagedContext:self.managedObjectContext];
    //[PlayerManagedObject playerWithResult:testplayer3 inManagedContext:self.managedObjectContext];
    //[self saveContext];
    
    [self fetchHistoryData:PVP];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

/*
#pragma core data retrieval

- (void)fetchHistoryData:(BOOL)matchType
{
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    NSManagedObjectContext *context = [appDelegate managedObjectContext];
    
    NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Game" inManagedObjectContext:context];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    
    [request setEntity:entityDesc];
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"(human = %d)",human];
        
    [request setPredicate:pred];
    
    //NSManagedObject *matches = nil;
    NSError *error;
    
    NSArray *objects = [context executeFetchRequest:request error:&error];
    
    [statArray removeAllObjects];
    if ([objects count] == 0) {
        if(human){
            NSLog(@"No statistics for humans");
            [statArray addObject:@"No Player Statistics"];
        } else {
            NSLog(@"No statistics for computers");
            [statArray addObject:@"No Computer Statistics"];
        }
        
    } else {
        [statArray addObject:@"we have entries"];
        //[statArray addObjectsFromArray:objects];
        //address.text = [matches valueForKey:@"address"];
        //phone.text = [matches valueForKey:@"phone"];
        //status.text = [NSString stringWithFormat:@"%d matches found", [objects count]];
    }
    [table reloadData];

}
 */

- (void)didSelectPlayer:(id)sender
{
    [self fetchHistoryData:![sender selectedSegmentIndex]];
    [table reloadData];
    /*
    switch (self.segcomp.selectedSegmentIndex) {
        case 0:
            //[self fetchRecords:NO];
            break;
        case 1:
            //[self fetchRecords:YES];
            break;
        default:
            NSLog(@"Selected incorrect player class");
            break;
    }*/
}

#pragma table delegate methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    //return 1;
    return [[self.fetchedResultsController sections] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];
    /*
    printf("%d\n",[statArray count]);
    if([statArray count] == 0){
        NSLog(@"Shouldn't be zero, handled by coredata");
        [statArray addObject:@"No Statistics Available"];
    }
    return [statArray count];*/
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"HistoryIdentifier";
    
    
    // Try to retrieve from the table view a now-unused cell with the given identifier.
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    // If no cell is available, create a new one using the given identifier.
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
	// Set up the cell.
	[self configureCell:cell atIndexPath:indexPath];

    return cell;
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }   
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     */
}

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
    
    cell.textLabel.text = [NSString stringWithFormat:@"%@ vs. %@",
                           [[managedObject valueForKey:@"player1"] description],
                           [[managedObject valueForKey:@"player2"] description]];
    
    /*if ([[managedObject valueForKey:@"draw"] isEqualToNumber:[NSNumber numberWithBool:YES]]) {
        cell.detailTextLabel.text = @"Match ended in a draw";
    }
    else {
        cell.detailTextLabel.text = 
        [NSString stringWithFormat:@"%@ won the match!", 
         [[managedObject valueForKey:@"player1"] description]];
    }*/
}

#pragma mark - Fetched results controller

- (NSFetchedResultsController *)fetchedResultsController
{
    if (__fetchedResultsController != nil) {
        return __fetchedResultsController;
    }
    
    // Set up the fetched results controller.
    // Create the fetch request for the entity.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = [NSEntityDescription entityForName:@"Game" inManagedObjectContext:self.managedObjectContext];
    request.fetchBatchSize = FETCHSIZE;
    request.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    request.predicate = nil;
    
    NSFetchedResultsController *c = [[NSFetchedResultsController alloc]
                                     initWithFetchRequest:request
                                     managedObjectContext:self.managedObjectContext
                                     sectionNameKeyPath:nil
                                     cacheName:nil];
    c.delegate = self;
    self.fetchedResultsController = c;
    
    return __fetchedResultsController;
}

- (void)fetchHistoryData:(BOOL)matchType
{
    self.fetchedResultsController.fetchRequest.predicate = [NSPredicate predicateWithFormat:@"pvp == %d", matchType];
    
    NSError *error;
    BOOL success = [self.fetchedResultsController performFetch:&error];
    if (!success) {
        NSLog(@"exception while fetching history  %@, %@", error, [error userInfo]);
    }
}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    [table reloadData];
}

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil)
    {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
        {
            /*
             Replace this implementation with code to handle the error appropriately.
             
             abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
             */
            NSLog(@"exception while saving context %@, %@", error, [error userInfo]);
            abort();
        } 
    }
}

@end
